package com.atguigu.tingshu.user.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.*;
import com.atguigu.tingshu.user.client.VipServiceConfigFeignClient;
import com.atguigu.tingshu.user.factory.StrategyFactory;
import com.atguigu.tingshu.user.mapper.*;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.sound.midi.Track;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private UserPaidAlbumMapper userPaidAlbumMapper;

	@Autowired
	private UserPaidTrackMapper userPaidTrackMapper;

	@Autowired
	private TrackInfoFeignClient trackInfoFeignClient;

	@Autowired
	private VipServiceConfigFeignClient vipServiceConfigFeignClient;

	@Autowired
	private UserVipServiceMapper userVipServiceMapper;

	@Autowired
	private VipServiceConfigMapper vipServiceConfigMapper;

	@Autowired
	private StrategyFactory strategyFactory;


	@Override
	public UserInfoVo getUserInfoVo(Long userId) {
		//获取缓存中用户数据
		UserInfo userInfo = this.getById(userId);
		UserInfoVo userInfoVo = new UserInfoVo();
		//属性拷贝
		BeanUtils.copyProperties(userInfo,userInfoVo);
		return userInfoVo;
	}

	@Override
	public Map<Long, Integer> userIsPaidTrack(Long userId, Long albumId, List<Long> trackIdList) {
		//表结构 user_paid_track
		// select * from user_paid_track where album_id = user_id  = ?
		UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getAlbumId, albumId).eq(UserPaidAlbum::getUserId, userId));
		//判断
		if (null != userPaidAlbum){
			//	购买过这个专辑.
			Map<Long, Integer> map = trackIdList.stream().collect(Collectors.toMap(trackId -> trackId, trackId -> 1));
			//	返回数据
			return map;
		} else {
			//	用户没有购买过专辑，判断用户是否购买过声音Id user_paid_track
			//	select * from user_paid_track where user_id = ? and track_id in (?,?,?);
			LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(UserPaidTrack::getUserId, userId).in(UserPaidTrack::getTrackId, trackIdList);
			List<Long> trackIdPaidList = userPaidTrackMapper.selectList(wrapper).stream().map(userPaidTrack -> userPaidTrack.getTrackId()).collect(Collectors.toList());
			//	创建一个map 集合
			Map<Long, Integer> map = new HashMap<>();
			//	循环遍历.
			trackIdList.stream().forEach(trackId -> {
				//	判断用户是否购买过声音Id
				if (trackIdPaidList.contains(trackId)) {
					//	购买过声音
					map.put(trackId, 1);
				} else {
					//	没有购买声音
					map.put(trackId, 0);
				}
			});
			return map;
		}
	}

	@Override
	public Boolean isPaidAlbum(Long albumId, Long userId) {
		//	select * from user_paid_album where album_id = ? and user_id = ?;
		return userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getAlbumId, albumId).eq(UserPaidAlbum::getUserId, userId)) != null;
	}


	@Override
	public List<Long> findUserPaidTrackList(Long albumId, Long userId) {
		//  select * from user_paid_track where user_id = 26 and album_id = 1429;
		return userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getAlbumId, albumId).eq(UserPaidTrack::getUserId, userId)).stream().map(userPaidTrack -> userPaidTrack.getTrackId()).collect(Collectors.toList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
		try {
			//  使用工厂调用策略模式
			ItemTypeStrategy typeStrategy = strategyFactory.getStrategy(userPaidRecordVo.getItemType());
			//  直接调用保存信息方法
			typeStrategy.savePaidRecord(userPaidRecordVo);
			//记录用户购买记录 专辑   声音    vip
			/*if (userPaidRecordVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_ALBUM)){
			UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getUserId,userPaidRecordVo.getUserId()).eq(UserPaidAlbum::getAlbumId,userPaidRecordVo.getItemIdList().get(0)));
			if (null != userPaidAlbum){
				return;
			}
			//创建对象
			userPaidAlbum = new UserPaidAlbum();
			userPaidAlbum.setAlbumId(userPaidRecordVo.getItemIdList().get(0));
			userPaidAlbum.setUserId(userPaidRecordVo.getUserId());
			userPaidAlbum.setOrderNo(userPaidRecordVo.getOrderNo());
			//保存数据
			userPaidAlbumMapper.insert(userPaidAlbum);
		}else if ( userPaidRecordVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_TRACK)){
			//声音 user_paid_track
			Long count = userPaidTrackMapper.selectCount(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getUserId, userPaidRecordVo.getUserId()).eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo()));
			if (count>0){
				return;
			}
			//创建对象并保存数据
			List<Long> itemIdList = userPaidRecordVo.getItemIdList();
			//需要根据声音id获取声音对象
			Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(itemIdList.get(0));
			Assert.notNull(trackInfoResult,"trackInfoResult不能为空");
			TrackInfo trackInfo = trackInfoResult.getData();
			Assert.notNull(trackInfo,"trackInfo不能为空");
			if (!CollectionUtils.isEmpty(itemIdList)){
				for (Long trackId : itemIdList){
					UserPaidTrack userPaidTrack	= new UserPaidTrack();
					//赋值
					userPaidTrack.setTrackId(trackId);
					userPaidTrack.setUserId(userPaidRecordVo.getUserId());
					userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
					//  获取专辑对象：才能赋值专辑Id;
					userPaidTrack.setAlbumId(trackInfo.getAlbumId());
					userPaidTrackMapper.insert(userPaidTrack);
				}
			}
		}else {
			// vip user_vip_service
			//需要获取用户的身份信息
			UserInfo userInfo = this.getById(userPaidRecordVo.getUserId());
			//  还需要获取到用户购买有效期！
			Long serviceId = userPaidRecordVo.getItemIdList().get(0);
			VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(serviceId);
			//  创建对象：
			UserVipService userVipService = new UserVipService();
			userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
			userVipService.setUserId(userPaidRecordVo.getUserId());
			userVipService.setStartTime(new Date());
			//  创建对象
			LocalDateTime localDateTime = new LocalDateTime(new Date());
			//  判断续期情况：当前用户属于VIP 并且 过期时间在系统时间之后！
			if (userInfo.getIsVip() == 1 && userInfo.getVipExpireTime().after(new Date())) {
				//  在过期时间基础上+购买时间;
				Date vipExpireTime = userInfo.getVipExpireTime();
				//  创建localDateTime
				localDateTime = new LocalDateTime(vipExpireTime);
			}
			//  获取过期时间
			Date vipExpireTime = localDateTime.plusMonths(vipServiceConfig.getServiceMonth()).toDate();
			//  设置过期时间
			userVipService.setExpireTime(vipExpireTime);
			//  保存数据
			userVipServiceMapper.insert(userVipService);

			//int i = 1/0;
			//  修改用户的vip状态
			userInfo.setIsVip(1);
			userInfo.setVipExpireTime(vipExpireTime);
			//  更新数据:
			this.updateById(userInfo);
		}*/
	} catch (Exception e) {
		System.out.println(e.getMessage());
		//抛出异常
		throw new GuiguException(ResultCodeEnum.SERVICE_ERROR);
	}


	}
}
